package com.qf.java2105.huangchuang.hotel.utils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;

/**
 * 上传文件工具
 * @author hcvg
 * @version v1.0
 * @date 2021/09/12
 **/
public class UploadFileUtils {
    public static String uploadFile(HttpServletRequest request, String uploadName, String uploadPath){
        try {
            // 上传图片
            Part part = request.getPart(uploadName);
            String fileName = part.getSubmittedFileName();
            if ("".equals(fileName) || null == fileName){
                fileName = "";
                return fileName;
            }
            // 获取上传图片后缀名
            String extName = MyStringUtils.getExtName(fileName);
            // 重命名图片
            fileName = MyStringUtils.getUuid().concat(extName);
            String destPath = request.getServletContext().getRealPath(uploadPath);
            File file = new File(destPath, fileName);
            // 确保图片地址存在，然后上传到服务器中
            if (!file.getParentFile().exists()){
                file.getParentFile().mkdirs();
            }
            part.write(file.getPath());
            return uploadPath + fileName;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
